package com.secure.orm.thirdPay.bill99;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.secure.common.util.PayUtil;
import com.secure.orm.enums.PayType;
import com.secure.orm.enums.PaymentOrderType;
import com.secure.orm.enums.ThirdPayNotifyType;
import com.secure.orm.model.PayOrder;
import com.secure.orm.model.response.ViewData;
import com.secure.orm.thirdPay.AbstractThirdPay;

public class Bill99 extends AbstractThirdPay {
	protected static Log logger = LogFactory.getLog(Bill99.class);

	public Bill99() {

	}

	@Override
	public Object pay(PayOrder payOrder) {
		Map<String, String> sParaTemp = new HashMap<String, String>();
		int totalFee = PayUtil.mulToInt(String.valueOf(payOrder.getOrderAmount()), String.valueOf(100));
		sParaTemp.put("inputCharset", "1");
		sParaTemp.put("bgUrl", properties.getProperty("base.domain")+properties.getProperty("bill99.bg_url")); // 接收快钱通知的URL
		sParaTemp.put("version", Bill99Config.VERSION);
		sParaTemp.put("language", "1");
		sParaTemp.put("signType", Bill99Config.sign_type);
		sParaTemp.put("merchantAcctId", properties.getProperty("bill99.partner"));
		sParaTemp.put("orderId", payOrder.getOrderId());
		sParaTemp.put("orderAmount",totalFee+ ""); // 商品金额,以分为单位
		sParaTemp.put("orderTime", PayUtil.formatTime(new Date(), "yyyyMMddHHmmss"));
		sParaTemp.put("productName", payOrder.getSubject());
		sParaTemp.put("productNum", "1");
		sParaTemp.put("ext1", payOrder.getUserId());
		sParaTemp.put("ext2", payOrder.getSubject());
		sParaTemp.put("payType", "00");
		sParaTemp.put("key", properties.getProperty("bill99.key"));
		String sign = getBillSign(payOrder);
		sParaTemp.put("signMsg", sign);
		return PayUtil.buildForm(properties.getProperty("bill99.geteway_url"), sParaTemp, "POST");
	}

	// 处理块钱 通知返回的参数
	@Override
	public Object handleResponse(Map<String, String> reqMap, ThirdPayNotifyType thirdPayNotifyType) {
		ViewData view = verifyThirdPayResponse(reqMap) ;
		String tradeStatus = reqMap.get("payResult") ;
		String tradeErrMsg = reqMap.get("errCode") ;
		String orderId = reqMap.get("orderId");
		Map<String,Object> resultMap = new HashMap<String,Object>();
		
		if(view.getCode()!=0){
			resultMap.put(orderId, PayType.Bill99.name() + "notify verify fail");
		}else{
			//交易成功
			if(Bill99Config.pay_result_success.equals(tradeStatus)){
				resultMap.put(orderId, PayType.Bill99.name()+PaymentOrderType.SCCUESS.name());
			}else{
				resultMap.put(orderId, PayType.Bill99.name() + tradeErrMsg);
			}
		}
		view.setResult(resultMap);
		return view;
	}
	
	
	public String getBillSign(PayOrder payOrder){
		// 注意：快钱MD5的顺序如下，不可改变，否则签名出错
		StringBuffer buffer = new StringBuffer();
		int totalFee = PayUtil.mulToInt(String.valueOf(payOrder.getOrderAmount()), String.valueOf(100));
		buffer.append("inputCharset=1").append("&");
		buffer.append("bgUrl=").append(properties.getProperty("base.domain")+properties.getProperty("bill99.bg_url")).append("&");
		buffer.append("version=").append(Bill99Config.VERSION).append("&");
		buffer.append("language=").append("1").append("&");
		buffer.append("signType=").append(Bill99Config.sign_type).append("&");
		buffer.append("merchantAcctId=").append(properties.getProperty("bill99.partner")).append("&");
		buffer.append("orderId=").append(payOrder.getOrderId()).append("&");
		buffer.append("orderAmount=").append(totalFee+"").append("&");
		buffer.append("orderTime=").append(PayUtil.formatTime(new Date(), "yyyyMMddHHmmss")).append("&");
		buffer.append("productName=").append(payOrder.getSubject()).append("&");
		buffer.append("productNum=").append("1").append("&");
		buffer.append("ext1=").append(payOrder.getUserId()).append("&");
		buffer.append("ext2=").append(payOrder.getSubject()).append("&");
		buffer.append("payType=").append("00").append("&");
		buffer.append("key=").append(properties.getProperty("bill99.key"));
		String sign = "";
		try {
			sign = MD5Util.md5Hex(buffer.toString().getBytes("utf-8")).toUpperCase();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return sign;
	}
	
	public String getKuaiqianSign(Map<String, String> Params){
		StringBuffer buffer = new StringBuffer();
		buffer.append("inputCharset=1").append("&");
		buffer.append("bgUrl=")
				.append(properties.getProperty("base.domain")+properties.getProperty("bill99.bg_url"))
				.append("&");
		buffer.append("version=").append(Bill99Config.VERSION).append("&");
		buffer.append("language=").append("1").append("&");
		buffer.append("signType=").append(Bill99Config.sign_type).append("&");
		buffer.append("merchantAcctId=").append(properties.getProperty("bill99.partner"))
				.append("&");
		buffer.append("orderId=").append(Params.get(Bill99Config.trade_no)).append("&");
		buffer.append("orderAmount=")
				.append(Params.get(Bill99Config.total_fee)).append("&");
		buffer.append("orderTime=").append(PayUtil.formatTime(new Date(), "yyyyMMddHHmmss"))
				.append("&");
		buffer.append("productName=").append(Params.get(Bill99Config.subject))
				.append("&");
		buffer.append("productNum=").append("1").append("&");
		buffer.append("ext1=").append(Params.get(Bill99Config.buyer_id)).append("&");
		buffer.append("ext2=").append(Params.get(Bill99Config.subject)).append("&");
		buffer.append("payType=").append("00").append("&");
		buffer.append("key=").append(properties.getProperty("bill99.key"));
		String sign = "";
		try {
			sign = MD5Util.md5Hex(buffer.toString().getBytes("utf-8"))
					.toUpperCase();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		logger.warn("---kuai_qian_request----sign--->" + buffer.toString() + "----sign--->" + sign);
		return sign;
	}
	
	private ViewData verifyThirdPayResponse(Map<String,String> requestParamsMap){
		boolean verify_result = getKuaiQianSignVeryfy(requestParamsMap);
		if (!verify_result) {
			return new ViewData(-1, "verify fail", null);
		}
		return new ViewData(0, "verify success", null);
	}
	
	public boolean getKuaiQianSignVeryfy(Map<String, String> params) {
    	String sign = params.get("signMsg");
        //获得签名验证结果
        String md5 = getKuaiqianSign(params);
        boolean isSign = md5.equals(sign);
        return isSign;
    }

}
